package org.jl.spring.aop.annotation;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class SysLogAspect {

    @Pointcut("@annotation(SysLog)")
    public void log() {
    }

    /**
     * 加入注解自动记录方法日志
     */
    @Around(value = "log()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取执行方法的类的名称（包名加类名）
        String className = joinPoint.getTarget().getClass().getName();
        // 获取实例和方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = method.getAnnotation(SysLog.class);
        String route = "";
        if (!ObjectUtils.isEmpty(sysLog.from())) {
            route = ",from " + sysLog.from() + " to " + sysLog.to();
        }
        // 记录日志
        log.info(className + "." + method.getName() + "()" + route);
        Object[] args = joinPoint.getArgs();
        if (args.length == 0) {
            log.info("Params ===》 not params");
        } else {
            log.info("Params ===》 " + JSON.toJSONString(args));
        }
        // 执行方法获取返回值
        Object proceed = joinPoint.proceed();
        // 记录日志
        if (proceed == null) {
            log.info("Returns ===》 not result");
        } else {
            log.info("Returns ===》 " + JSON.toJSONString(proceed));
        }
        // 返回
        return proceed;
    }

}
